// 立即执行，但停止后无法执行最后一次
function throttle(func, wait) {
  let previous = 0;

  return function (...args) {
    let now = +new Date();
    if (now - previous > wait) {
      func.apply(this, args);
      previous = now;
    }
  }
}

// 立即执行，停止后还可以执行最后一次
function throttle(func, wait) {
  let timeout;

  return function (...args) {
    if (!timeout) {
      timeout = setTimeout(() => {
        timeout = null;
      }, wait)
      func.apply(this, args);
    }
  }
}

function throttle(fn, wait, immediate) {
  let timer = null
  let callNow = immediate

  return function (...args) {
    if (callNow) {
      fn.apply(this, args)
      callNow = false
    }

    if (!timer) {
      timer = setTimeout(() => {
        fn.apply(this, args)
        timer = null
      }, wait)
    }
  }
}